package com.wqh.apigateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


/**
 * @author wanqh
 * @date 2018/01/18 9:33
 * @description:
 */
@Component
public class AccessFilter extends ZuulFilter{
    private static final Logger logger = LoggerFactory.getLogger(AccessFilter.class);
    /**
     * 过滤器类型，他决定过滤器在请求的哪个生命周期执行。
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 过滤器的知心顺序，
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 判断过滤器是否需要执行
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器的具体逻辑
     * @return
     */
    @Override
    public Object run() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        logger.info("send{} request to {}",request.getMethod(),request.getRequestURI().toCharArray());
        String accessToken = request.getParameter("accessToken");
        if(StringUtils.isBlank(accessToken)){
            logger.warn("accessToken is empty");
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(401);
            return null;
        }
        logger.info("accessToken {}" ,accessToken);
        return null;
    }
}
